import React, { useState } from 'react'
import { Button, Drawer, message, Modal, Popconfirm, Space, Table, Typography } from 'antd'
import useGetTableData from '@/hooks/useGetTableDataNoPagination'
import { getAllRouteTree, addRoutes, editRoutes, delRouteById } from '@/api/system'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import './index.less'
import { IOptionType, ITableData } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import { useFormEdit, useFormFuncEdit } from './useFormEdit'
import { AppListOptions } from '@/constant'
import { PlusOutlined } from '@ant-design/icons'
import { onValuesChange } from '@/utils/onValuesChange'
const Index: React.FC = () => {
  const [form] = useForm()
  const [FormEdit] = useForm()
  const [FormEditFunc] = useForm()
  const [isModalShow, setIsModalShow] = useState(false)
  const [isEdit, setIsEdit] = useState(false)
  const [isFuncShow, setIsFuncShow] = useState(false)
  const [isFuncEdit, setIsFuncEdit] = useState(false)
  const [isShowFuncList, setisShowFuncList] = useState(false)
  const [ispedding, setispedding] = useState<boolean>(false)
  const [funcList, setfuncList] = useState<ITableData[]>([])
  const [currentInfo, setcurrentInfo] = useState<Record<string, any>>({})
  const { tableProps, params, search, reset } = useGetTableData<ITableData>(getAllRouteTree, {
    form: form,
    pageSize: 999,
    immediatelySend: false,
  })
  const formatList = (list: ITableData[]): IOptionType => {
    return list?.map((item: ITableData) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
        children: Array.isArray(item.children) ? formatList(item.children) : [],
      }
    })
  }
  const onConfirm = async (values: any) => {
    setispedding(true)
    const id = FormEdit.getFieldValue('id')
    let res
    if (!isEdit) {
      res = await addRoutes({ ...values, applicationId: form.getFieldValue('applicationId') }).finally(() =>
        setispedding(false),
      )
    } else {
      res = await editRoutes({ id, ...values, applicationId: form.getFieldValue('applicationId') }).finally(() =>
        setispedding(false),
      )
    }
    if (res.code === 200) {
      message.success('操作成功')
      onCancel()
      search(params)
    }
  }
  const onCancel = () => {
    setIsModalShow(false)
    FormEdit.resetFields()
  }
  const onEdit = (info: ITableData) => {
    FormEdit.setFieldsValue(info)
    setIsEdit(true)
    setIsModalShow(true)
  }
  const onDel = async (id: number) => {
    const res = await delRouteById([id])
    if (res.code === 200) {
      message.success('操作成功')
      onCancel()
      onFuncCancel()
      setisShowFuncList(false)
      search(params)
    }
  }
  const onFuncCancel = () => {
    setIsFuncShow(false)
    FormEditFunc.resetFields()
  }
  const onFuncConfirm = async (values: any) => {
    if (!values.interfaceUrl && !values.buttonCode) {
      message.warning('功能地址与按钮编码至少填写一项')
      return
    }
    setispedding(true)
    let res
    if (!isFuncEdit) {
      res = await addRoutes({
        ...values,
        type: 'FUNCTION',
        applicationId: form.getFieldValue('applicationId'),
      }).finally(() => setispedding(false))
    } else {
      res = await editRoutes({
        ...currentInfo,
        ...values,
        type: 'FUNCTION',
        applicationId: form.getFieldValue('applicationId'),
      }).finally(() => setispedding(false))
    }
    if (res.code === 200) {
      message.success('操作成功')
      onFuncCancel()
      setisShowFuncList(false)
      search(params)
      setcurrentInfo({})
    }
  }
  const onFuncEdit = (info: ITableData) => {
    setcurrentInfo(info)
    FormEditFunc.setFieldsValue(info)
    setIsFuncEdit(true)
    setIsFuncShow(true)
    setisShowFuncList(false)
    setfuncList([])
  }
  const showFuncList = (info: ITableData) => {
    setisShowFuncList(true)
    setfuncList(info?.function || [])
  }
  return (
    <PageContainer>
      <SearchForm
        params={params!}
        form={form}
        searchConfig={[
          {
            label: '所属应用',
            name: 'applicationId',
            type: 'Select',
            option: AppListOptions,
            rules: [{ required: true, message: '请选择所属应用' }],
          },
        ]}
        onFinish={(vals: any) => {
          search(vals)
        }}
        onReset={() => {
          reset()
        }}
        extra={
          <Space>
            <Button
              type="primary"
              onClick={() => {
                if (!form.getFieldValue('applicationId')) {
                  message.warning('请选择所属应用')
                  return
                }
                setIsModalShow(true)
                setIsEdit(false)
              }}
              icon={<PlusOutlined />}
            >
              新建路由
            </Button>
            <Button
              type="primary"
              onClick={() => {
                if (!form.getFieldValue('applicationId')) {
                  message.warning('请选择所属应用')
                  return
                }
                setIsFuncShow(true)
                setIsFuncEdit(false)
              }}
              icon={<PlusOutlined />}
            >
              新建功能
            </Button>
          </Space>
        }
      ></SearchForm>
      <div className="custom_table_style">
        <Table
          bordered
          columns={useIndexColumns(onEdit, showFuncList, onDel)}
          {...tableProps}
          rowKey="id"
          scroll={{ x: window.innerWidth - 300 }}
          rowHoverable={false}
          rowClassName={(_, index) => {
            return index % 2 === 0 ? '' : 'zebra-row-odd'
          }}
          pagination={false}
        />
      </div>
      <Drawer
        title={isFuncEdit ? '编辑功能' : '新建功能'}
        maskClosable
        open={isFuncShow}
        onClose={onFuncCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onFuncCancel}>取消</Button>
              <Button
                loading={ispedding}
                type="primary"
                onClick={() => FormEditFunc.validateFields().then((values) => onFuncConfirm(values))}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={useFormFuncEdit({
            data: formatList(tableProps?.dataSource),
          })}
          form={FormEditFunc}
          onValuesChange={(changedValues) => onValuesChange(changedValues, ['name', 'interfaceUrl'], FormEditFunc)}
        />
      </Drawer>
      <Drawer
        title={isEdit ? '编辑路由' : '新建路由'}
        maskClosable
        open={isModalShow}
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button
                loading={ispedding}
                type="primary"
                onClick={() => FormEdit.validateFields().then((values) => onConfirm(values))}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={useFormEdit({
            data: formatList(tableProps?.dataSource),
          })}
          form={FormEdit}
          initialValues={{ type: 'MENU', cache: 0 }}
          onValuesChange={(changedValues) =>
            onValuesChange(changedValues, ['name', 'path', 'fullPath', 'resourcePath', 'icon'], FormEdit)
          }
        />
      </Drawer>
      <Modal
        wrapClassName="function_modal_wrap"
        title="功能列表"
        maskClosable
        open={isShowFuncList}
        width={800}
        footer={null}
        onCancel={() => {
          setisShowFuncList(false)
          setfuncList([])
        }}
      >
        <div className="custom_table_style">
          <Table
            dataSource={funcList}
            pagination={false}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
            bordered
            columns={[
              {
                title: '功能名称',
                dataIndex: 'name',
                key: 'name',
                align: 'center',
              },
              // {
              //   title: '接口地址',
              //   dataIndex: 'interfaceUrl',
              //   key: 'interfaceUrl',
              //   align: 'center',
              // },
              {
                title: '按钮编码',
                dataIndex: 'buttonCode',
                key: 'buttonCode',
                align: 'center',
              },
              {
                fixed: 'right',
                title: '操作',
                align: 'center',
                render: (info) => {
                  return (
                    <Space size="large">
                      <Typography.Link
                        onClick={() => {
                          onFuncEdit(info)
                        }}
                      >
                        功能编辑
                      </Typography.Link>
                      <Popconfirm
                        title={`确认删除吗？`}
                        onConfirm={() => onDel(info.id)}
                        okText="确认"
                        cancelText="取消"
                      >
                        <Typography.Link>删除</Typography.Link>
                      </Popconfirm>
                    </Space>
                  )
                },
              },
            ]}
          ></Table>
        </div>
      </Modal>
    </PageContainer>
  )
}

export default Index
